<script setup>
import SearchForm from '@/components/Search-Form.vue'
import TableBase from '@/components/Table-Base.vue'
import TablePagination from '@/components/Table-Pagination.vue'
import DialogBase from '@/components/Dialog-Base.vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { CheckIcon, CloseIcon  } from 'tdesign-icons-vue-next'
import { ref } from 'vue'
import { addUserItem, delUserItem, editUserItem, getUserList, getUserItem, resetPassword } from '@/api/employee'
import { getRolesList } from '@/api/roles'
import MainContent from '@/components/Main-Content.vue'

const formData = ref({})
const query = ref({
    page: 1,
    pageSize: 10
})
const listData = ref({
    list: [],
    total: 0
})
const rules = ref({
    name: [
        { required: true, message: '请输入员工姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    phonenumber: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { pattern: /^1\d{10}$/, message: '请输入正确的手机号码' }
    ],
    userName: [
        { required: true, message: '请输入登录账号', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    roleId: [
        { required: true, message: '请输入角色', trigger: 'blur' }
    ]
})
const columns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '员工姓名',
        colKey: 'name'
    },
    {
        title: '登录账号',
        colKey: 'userName'
    },
    {
        title: '联系方式',
        colKey: 'phonenumber'
    },
    {
        title: '角色',
        colKey: 'roleName'
    },
    {
        title: '状态',
        colKey: 'status'
    },
    {
        title: '添加时间',
        colKey: 'createTime',
        width: 180
    },
    {
        title: '操作',
        colKey: 'option',
        width: 220
    }
])
const showDialog = ref(false)
const dialogType = ref('add')
const dialogForm = ref({
    status: 0
})
const rolesList = ref([])
const dialogFormInstance = ref(null)

const search = async () => {
    const res = await getUserList({
        ...query.value,
        ...formData.value
    })
    listData.value.list = res.data.rows.map(e => {
        if (e.status === 2) e.status = 1
        e.status === 1 ? e.status = '启用' : e.status = '停用'
        return e
    })
    listData.value.total = res.data.total
}
const reset = () => {
    formData.value = {}
    search()
}
const addUser = async () => {
    dialogType.value = 'add'
    showDialog.value = true
    rolesList.value = (await getRolesList()).data
}
const closeDialog = () => {
    showDialog.value = false
    if (dialogFormInstance.value) dialogFormInstance.value.clearValidate()
}
const clickClose = () => {
    showDialog.value = false
    if (dialogFormInstance.value) dialogFormInstance.value.reset()
    dialogForm.value = { status: 0 }
}
const dialogConfirm = async () => {
    const valid = await dialogFormInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        if (dialogType.value === 'add') {
            if (!('status' in dialogForm.value)) dialogForm.value.status = 0
            const res = await addUserItem(dialogForm.value)
            if (res.code !== 10000) return
            clickClose()
            await MessagePlugin.success('添加成功！')
            await search()
        } else {
            delete dialogForm.value.createTime
            const res = await editUserItem(dialogForm.value)
            if (res.code !== 10000) return
            clickClose()
            await MessagePlugin.success('修改成功！')
            await search()
        }
    }
}
const getRow = async (data, type) => {
    if (type === 'edit') {
        dialogType.value = 'edit'
        showDialog.value = true
        const res = (await getUserItem(data.row.id)).data
        if (res.status === 2) res.status = 1
        dialogForm.value = res
        rolesList.value = (await getRolesList()).data
    } else if (type === 'del') {
        const res = await delUserItem(data.row.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            if (listData.value.list.length === 1 && query.value.page > 1) query.value.page--
            await search()
        } else {
            await MessagePlugin.error(res.msg)
        }
    } else {
        const res = await resetPassword({
            id: data.row.id
        })
        if (res.code !== 10000) return
        await MessagePlugin.success('重置成功！')
    }
}
const changePage = e => {
    query.value.page = e.current
    query.value.pageSize = e.pageSize
    search()
}

search()
</script>

<template>
    <main-content>
        <search-form>
            <t-form
                ref="form"
                :data="formData"
                label-width="auto"
                layout="inline"
            >
                <t-form-item label="员工姓名">
                    <t-input v-model.trim="formData.name" placeholder="请输入员工姓名"></t-input>
                </t-form-item>
                <t-form-item style="min-width: auto">
                    <t-button @click="search" type="submit" style="margin-right: 10px;">查询</t-button>
                    <t-button @click="reset" variant="outline">重置</t-button>
                </t-form-item>
            </t-form>
        </search-form>

        <table-base :columns="columns" :list="listData.list">
            <template #top-btn>
                <t-button theme="primary" @click="addUser">添加员工</t-button>
            </template>
            <template #option-table="row">
                <t-button variant="text" theme="primary" @click="getRow(row, 'edit')">编辑</t-button>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'del')"
                    theme="warning" content="确认删除吗">
                    <t-button variant="text" theme="primary">删除</t-button>
                </t-popconfirm>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'resetPassword')"
                    theme="warning" content="确认要把密码重置为 123456 吗">
                    <t-button variant="text" theme="primary">重置密码</t-button>
                </t-popconfirm>
            </template>
        </table-base>

        <table-pagination :total="listData.total" @changePage="changePage"></table-pagination>

        <dialog-base :showDialog="showDialog"
                     :dialogType="dialogType"
                     :dialogTitle="dialogType === 'add' ? '添加员工' : '编辑员工'"
                     @dialogConfirm="dialogConfirm"
                     @clickClose="clickClose"
                     @closeDialog="closeDialog">
            <t-form class="dialogForm" ref="dialogFormInstance" labelAlign="top"
                    :rules="rules" :data="dialogForm">
                <t-form-item label="员工姓名" name="name">
                    <t-input placeholder="请输入员工姓名" v-model.trim="dialogForm.name"/>
                </t-form-item>
                <t-form-item label="联系方式" name="phonenumber">
                    <t-input-number placeholder="请输入联系方式"
                                    v-model.trim="dialogForm.phonenumber" theme="column"/>
                </t-form-item>
                <t-form-item label="登录账号" name="userName">
                    <t-input placeholder="请输入登录账号" v-model.trim="dialogForm.userName"/>
                </t-form-item>
                <t-form-item label="登录密码" name="password">
                    <t-input placeholder="请输入登录密码" value="123456" disabled/>
                </t-form-item>
                <t-form-item label="分配角色" name="roleId">
                    <t-select
                        filterable
                        placeholder="请选择角色"
                        v-model.trim="dialogForm.roleId"
                        showArrow>
                        <t-option v-for="e in rolesList" :value="e.roleId" :key="e.roleId" :label="e.roleName"/>
                    </t-select>
                </t-form-item>
                <t-form-item label="员工状态" name="status">
                    <t-switch size="large" :customValue="[1, 0]" v-model="dialogForm.status">
                        <template #label="slotProps">
                            <template v-if="slotProps.value">
                                <check-icon />
                            </template>
                            <template v-else>
                                <close-icon />
                            </template>
                        </template>
                    </t-switch>
                </t-form-item>
            </t-form>
        </dialog-base>
    </main-content>
</template>

<style scoped lang="scss">
.t-input-number {
    width: 100%;
}
</style>
